/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.lcp;

import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.api.lcp.StandardLcpExtend;
import com.inspur.edp.bef.api.parameter.retrieve.RespectiveRetrieveResult;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveParam;
import com.inspur.edp.cef.entity.accessor.entity.AccessorCollection;
import com.inspur.edp.cef.entity.accessor.entity.IEntityAccessor;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import java.util.List;
import java.util.Objects;

public class StandardLcpExtendImpl implements StandardLcpExtend {

  @Override
  public RespectiveRetrieveResult retrieveChildWithParent(IStandardLcp lcp, List<String> nodePath,
      List<String> idPath, RetrieveParam param) {
    //工作流子表/从从表提交审批需求, 检索结果要求是目标子表/从从表及其上级和下级数据, 排除同级及其上级的同级
    //使用copy的方法逐级复制, 排除同级数据.
    Objects.requireNonNull(lcp, "lcp");
    Objects.requireNonNull(nodePath, "nodePath");
    Objects.requireNonNull(idPath, "idPath");
    Objects.requireNonNull(param, "param");

    RespectiveRetrieveResult rez = lcp.retrieve(idPath.get(0), param);

    if (rez.getData() != null) {
      IEntityData currentSource = rez.getData();
      IEntityAccessor currentTarget = (IEntityAccessor) ((StandardLcp) lcp).getBEManager()
          .getAccessorCreator().createAccessor(currentSource.copySelf());
      rez.setData(currentTarget);
      for (int i = 0; i < nodePath.size(); ++i) {
        IEntityDataCollection sourceChildCollection = currentSource.getChilds()
            .get(nodePath.get(i));
        currentSource = (IEntityAccessor) (sourceChildCollection != null ? sourceChildCollection
            .tryGet(idPath.get(i + 1)) : null);
        if (currentSource == null) {
          rez.setData(null);
          break;
        }
        AccessorCollection newChildCollection = (AccessorCollection) currentTarget
            .createAndSetChildCollection(nodePath.get(i));
        if (i == nodePath.size() - 1) {
          currentTarget = (IEntityAccessor) currentSource.copy();
        } else {
          currentTarget = newChildCollection.createInstance();
          currentTarget.setInnerData(currentSource.copySelf());
        }
        newChildCollection.innerAdd(currentTarget);
      }
    }

    return rez;
  }
}
